package yunjiao.javatutorials.guava.concurrent.event;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;

/**
 * 消息队列集成示例
 *
 * @author yangyunjiao
 */
public class MessageQueueIntegrationExample {
    public static void main(String[] args) throws InterruptedException {
        EventProcessor processor = new EventProcessor();
        MessageConsumer consumer = new MessageConsumer(processor);

        // 发送请求
        ListenableFuture<String> future = processor.sendRequest("MSG-001", "重要的业务操作");

        Futures.addCallback(future, new FutureCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("业务操作成功: " + result);
                // 这里可以继续后续业务逻辑
            }

            @Override
            public void onFailure(Throwable throwable) {
                System.err.println("业务操作失败: " + throwable.getMessage());
                // 这里可以执行补偿操作
            }
        }, MoreExecutors.directExecutor());

        // 模拟消息消费者接收响应
        new Thread(() -> {
            try {
                Thread.sleep(2000);
                // 模拟成功响应
                consumer.onMessageReceived("MSG-001", "业务操作完成，数据已持久化");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }).start();

        Thread.sleep(3000);
        System.out.println("演示完成");
    }

    // 模拟消息消费者
    static class MessageConsumer {
        private EventProcessor eventProcessor;

        public MessageConsumer(EventProcessor eventProcessor) {
            this.eventProcessor = eventProcessor;
        }

        public void onMessageReceived(String requestId, String response) {
            // 这里模拟从消息队列接收消息
            System.out.println("接收到消息 - 请求ID: " + requestId + ", 响应: " + response);
            eventProcessor.handleResponse(requestId, response);
        }

        public void onErrorReceived(String requestId, String error) {
            System.out.println("接收到错误 - 请求ID: " + requestId + ", 错误: " + error);
            eventProcessor.handleError(requestId, error);
        }
    }

}
